package com.seu.vcampus.view.library;

import com.seu.vcampus.client.VCampusClient;
import com.seu.vcampus.message.Message;
import com.seu.vcampus.util.UIStyleUtil;
import com.seu.vcampus.vo.Book;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.UUID;

/**
 * 添加图书面板
 * 用于管理员添加新图书
 * 
 * @author 虚拟校园开发团队
 * @since 1.0.0
 */
public class AddBookPanel extends JPanel {
    private VCampusClient client;
    private Runnable onBookAddedListener;
    
    // 输入字段
    private JTextField bookIdField;
    private JTextField titleField;
    private JTextField authorField;
    private JTextField publisherField;
    private JTextField isbnField;
    private JTextField stockField;
    
    // 按钮
    private JButton confirmButton;
    private JButton cancelButton;
    
    public AddBookPanel(VCampusClient client) {
        this.client = client;
        initializeComponents();
        setupLayout();
        setupEventHandlers();
    }
    
    /**
     * 初始化组件
     */
    private void initializeComponents() {
        setLayout(new BorderLayout(15, 15));
        setBackground(UIStyleUtil.BACKGROUND_COLOR);
        setBorder(new EmptyBorder(20, 20, 20, 20));
        
        // 初始化输入字段
        bookIdField = UIStyleUtil.createModernTextField("系统将自动生成");
        bookIdField.setEditable(false);
        bookIdField.setText(UUID.randomUUID().toString().substring(0, 8));
        
        titleField = UIStyleUtil.createModernTextField("请输入书名");
        authorField = UIStyleUtil.createModernTextField("请输入作者");
        publisherField = UIStyleUtil.createModernTextField("请输入出版社");
        isbnField = UIStyleUtil.createModernTextField("请输入ISBN");
        stockField = UIStyleUtil.createModernTextField("请输入库存数量");
        
        // 初始化按钮
        confirmButton = UIStyleUtil.createPrimaryButton("确认添加");
        cancelButton = UIStyleUtil.createSecondaryButton("取消");
    }
    
    /**
     * 设置布局
     */
    private void setupLayout() {
        JPanel formPanel = new JPanel(new GridLayout(6, 2, 10, 10));
        formPanel.setBackground(UIStyleUtil.BACKGROUND_COLOR);
        
        // 添加表单字段
        formPanel.add(new JLabel("图书ID:"));
        formPanel.add(bookIdField);
        formPanel.add(new JLabel("书名:"));
        formPanel.add(titleField);
        formPanel.add(new JLabel("作者:"));
        formPanel.add(authorField);
        formPanel.add(new JLabel("出版社:"));
        formPanel.add(publisherField);
        formPanel.add(new JLabel("ISBN:"));
        formPanel.add(isbnField);
        formPanel.add(new JLabel("库存数量:"));
        formPanel.add(stockField);
        
        // 设置标签样式
        for (Component comp : formPanel.getComponents()) {
            if (comp instanceof JLabel) {
                ((JLabel) comp).setFont(UIStyleUtil.BODY_FONT);
                ((JLabel) comp).setForeground(UIStyleUtil.DARK_COLOR);
            }
        }
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
        buttonPanel.setBackground(UIStyleUtil.BACKGROUND_COLOR);
        buttonPanel.add(cancelButton);
        buttonPanel.add(confirmButton);
        
        add(formPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }
    
    /**
     * 设置事件处理器
     */
    private void setupEventHandlers() {
        confirmButton.addActionListener(this::confirmAddBook);
        cancelButton.addActionListener(e -> {
            if (getParent() instanceof JDialog) {
                ((JDialog) getParent()).dispose();
            }
        });
    }
    
    /**
     * 确认添加图书
     */
    private void confirmAddBook(ActionEvent e) {
        // 验证输入
        if (!validateInput()) {
            return;
        }
        
        // 创建图书对象
        Book book = new Book();
        book.setBookId(bookIdField.getText());
        book.setTitle(titleField.getText().trim());
        book.setAuthor(authorField.getText().trim());
        book.setPublisher(publisherField.getText().trim());
        book.setIsbn(isbnField.getText().trim());
        book.setStock(Integer.parseInt(stockField.getText().trim()));
        
        // 发送添加请求
        confirmButton.setEnabled(false);
        confirmButton.setText("添加中...");
        
        new Thread(() -> {
            try {
                Message request = new Message(Message.Type.ADD_BOOK_REQUEST);
                request.setPayload(book);
                
                Message response = client.sendMessage(request);
                
                if (response.getType() == Message.Type.ADD_BOOK_RESPONSE) {
                    String result = (String) response.getPayload();
                    SwingUtilities.invokeLater(() -> {
                        if ("SUCCESS".equals(result)) {
                            JOptionPane.showMessageDialog(this, 
                                "图书添加成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                            if (onBookAddedListener != null) {
                                onBookAddedListener.run();
                            }
                        } else {
                            JOptionPane.showMessageDialog(this, 
                                "添加失败：" + result, "错误", JOptionPane.ERROR_MESSAGE);
                            confirmButton.setEnabled(true);
                            confirmButton.setText("确认添加");
                        }
                    });
                }
            } catch (Exception ex) {
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(this, 
                        "添加失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    confirmButton.setEnabled(true);
                    confirmButton.setText("确认添加");
                });
            }
        }).start();
    }
    
    /**
     * 验证输入
     */
    private boolean validateInput() {
        if (titleField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入书名", "提示", JOptionPane.WARNING_MESSAGE);
            titleField.requestFocus();
            return false;
        }
        
        if (authorField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入作者", "提示", JOptionPane.WARNING_MESSAGE);
            authorField.requestFocus();
            return false;
        }
        
        if (publisherField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入出版社", "提示", JOptionPane.WARNING_MESSAGE);
            publisherField.requestFocus();
            return false;
        }
        
        if (isbnField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入ISBN", "提示", JOptionPane.WARNING_MESSAGE);
            isbnField.requestFocus();
            return false;
        }
        
        if (stockField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入库存数量", "提示", JOptionPane.WARNING_MESSAGE);
            stockField.requestFocus();
            return false;
        }
        
        try {
            int stock = Integer.parseInt(stockField.getText().trim());
            if (stock < 0) {
                JOptionPane.showMessageDialog(this, "库存数量不能为负数", "提示", JOptionPane.WARNING_MESSAGE);
                stockField.requestFocus();
                return false;
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "库存数量必须是整数", "提示", JOptionPane.WARNING_MESSAGE);
            stockField.requestFocus();
            return false;
        }
        
        return true;
    }
    
    /**
     * 设置图书添加完成监听器
     */
    public void setOnBookAddedListener(Runnable listener) {
        this.onBookAddedListener = listener;
    }
}